package fu.capstone.hanoicityguide.presentation.fragment.commondialogue;

import java.io.File;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SearchView;
import fu.capstone.hanoicityguide.R;
import fu.capstone.hanoicityguide.business.bo.commondialogue.CommonDialogueBO;
import fu.capstone.hanoicityguide.business.bo.commondialogue.CommonDialogueBOImp;
import fu.capstone.hanoicityguide.business.model.CommonDialogue;
import fu.capstone.hanoicityguide.common.utility.CacheCommonDialogues;
import fu.capstone.hanoicityguide.common.utility.InternetSetting;
import fu.capstone.hanoicityguide.presentation.adapter.ListCommonDialogueAdapter;

@SuppressLint("ValidFragment")
public class ListCommonDialogueFragment extends Fragment implements
		SearchView.OnQueryTextListener, SearchView.OnCloseListener {

	private CommonDialogueBO commondialogueBO;
	private ArrayList<CommonDialogue> arrCommonDialogue;
	private File[] listAudioFile;
	private InternetSetting internetSetting;
	private ListCommonDialogueAdapter adapter;
	private SearchView searchView;
	private String sorter;
	private String keyword;
	private String[] sorterArr;
	private DrawerLayout drawer;
	private ListView listCommonDialogue;

	public ListCommonDialogueFragment(DrawerLayout drawer) {
		this.drawer = drawer;
	}

	@Override
	public View onCreateView(final LayoutInflater inflater,
			final ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View listCommonDialogueFragment = inflater.inflate(
				R.layout.fragment_list_common_dialogue, container, false);
		try {
			setHasOptionsMenu(true);
			listCommonDialogue = (ListView) listCommonDialogueFragment
					.findViewById(R.id.listCommonDialogue);

			listAudioFile = null;
			arrCommonDialogue = new ArrayList<CommonDialogue>();
			commondialogueBO = new CommonDialogueBOImp(container.getContext());
			setKeyword("");
			setSorter(getResources().getStringArray(R.array.sorter_items)[3]);
			sorterArr = new String[2];
			sorterArr[0] = getResources().getStringArray(R.array.sorter_items)[2];
			sorterArr[1] = getResources().getStringArray(R.array.sorter_items)[3];

			arrCommonDialogue = commondialogueBO.listCommonDialogue(
					getKeyword(), getSorter());
			adapter = new ListCommonDialogueAdapter(getActivity(),
					R.layout.adapter_list_common_dialogue, arrCommonDialogue);
			listCommonDialogue.setAdapter(adapter);

			// CacheCommonDialogues.getListFile(container.getContext());
			final CacheCommonDialogues cacheCommonDialogue = new CacheCommonDialogues();
			internetSetting = new InternetSetting();

			// folder empty and no internet connection
			// if (listAudioFile.length == 0 &&
			// !internetSetting.getConnectivityStatus(getActivity())){
			// internetSetting.showSettingsAlert();
			// }
			
			if(!internetSetting.getConnectivityStatus(container.getContext())) {
				internetSetting.showSettingsAlert();
			}	
			else if (internetSetting.getConnectivityStatus(container.getContext())) {
				for (int i = 0; i < arrCommonDialogue.size(); i++) {
					cacheCommonDialogue.writeFiletoCache(
							container.getContext(), arrCommonDialogue.get(i)
									.getAudioPath(), arrCommonDialogue.get(i)
									.getId());

				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

		return listCommonDialogueFragment;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// create option menu in actionbar
		inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.list_commondialogue_menu, menu);

		// Associate searchable configuration with the SearchView
		searchView = (SearchView) menu.findItem(R.id.action_search_dialogue)
				.getActionView();
		setupSearchView();
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// create event for items of option menu in actionbar
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		AlertDialog dialog;

		switch (item.getItemId()) {
		// show sorter dialog
		case R.id.action_sort_dialogue:
			builder.setTitle("Sort");
			builder.setItems(sorterArr, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int item) {
					// sort by sorter
					setSorter(getResources().getStringArray(
							R.array.sorter_items)[item + 2]);

					arrCommonDialogue = commondialogueBO.listCommonDialogue(
							getKeyword(), getSorter());

					// reset array common dialogue in adapter
					adapter.setArr(arrCommonDialogue);
					adapter.notifyDataSetChanged();
				}
			});

			dialog = builder.create();
			dialog.show();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume() {
		// on resume change the title of actionbar to common dialogue
		super.onResume();
		getActivity().getActionBar().setTitle("Common Dialogues");
	}

	public String getSorter() {
		return this.sorter;
	}

	public void setSorter(String sorter) {
		this.sorter = sorter;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public String getKeyword() {
		return this.keyword;
	}

	private void setupSearchView() {

		searchView.setIconifiedByDefault(false);
		searchView.setQueryHint("Dialogue");

		searchView
				.setOnQueryTextFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						// TODO Auto-generated method stub
						if (hasFocus) {
							drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
						} else {
							onClose();
						}
					}
				});

		searchView.setOnQueryTextListener(this);
		searchView.setOnCloseListener(this);
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		setKeyword(query);
		if (getKeyword() != null && getSorter() != null) {
			arrCommonDialogue = commondialogueBO.listCommonDialogue(
					getKeyword(), getSorter());
			adapter.setArr(arrCommonDialogue);
			adapter.notifyDataSetChanged();
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		// TODO Auto-generated method stub
		setKeyword(newText);

		if (getKeyword() != null && getSorter() != null) {
			arrCommonDialogue = commondialogueBO.listCommonDialogue(
					getKeyword(), getSorter());
			adapter.setArr(arrCommonDialogue);
			adapter.notifyDataSetChanged();
			return true;
		} else {
			return false;
		}

	}

	@Override
	public boolean onClose() {
		// onclose search view
		drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
		searchView.setQuery("", true);
		setKeyword("");
		arrCommonDialogue = commondialogueBO
				.listCommonDialogue("", getSorter());
		adapter.setArr(arrCommonDialogue);
		adapter.notifyDataSetChanged();
		return true;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		searchView = null;
		super.onDestroy();
	}

}
